<template>
  <div class="app-container ai-create-container">
    <!-- 欢迎界面 -->
    <div v-if="step === 'welcome'" class="welcome-section">
      <div class="hero">
        <h1 class="hero-title">
          <i class="el-icon-magic-stick" style="color: #1EB7E6;" />
          AI 创建网站
        </h1>
        <p class="hero-subtitle">只需描述你的想法，AI帮你创建完整的网站</p>
      </div>

      <div class="quick-start">
        <el-card class="start-card">
          <div class="card-content">
            <i class="el-icon-chat-dot-round card-icon" />
            <h3>开始对话</h3>
            <p>告诉AI你想要什么样的网站，它会帮你完成一切</p>
            <el-button
              type="primary"
              size="large"
              style="background-color: #1EB7E6; border-color: #1EB7E6; margin-top: 20px;"
              @click="startAICreate"
            >
              <i class="el-icon-magic-stick" /> 开始AI创建
            </el-button>
          </div>
        </el-card>

        <el-card class="start-card">
          <div class="card-content">
            <i class="el-icon-document-copy card-icon" />
            <h3>使用模板</h3>
            <p>从预设模板快速开始，AI帮你定制化</p>
            <el-button
              type="success"
              size="large"
              style="margin-top: 20px;"
              @click="showTemplates"
            >
              <i class="el-icon-folder-opened" /> 选择模板
            </el-button>
          </div>
        </el-card>

        <el-card class="start-card">
          <div class="card-content">
            <i class="el-icon-setting card-icon" />
            <h3>手动创建</h3>
            <p>完全自定义配置，适合高级用户</p>
            <el-button
              type="info"
              size="large"
              style="margin-top: 20px;"
              @click="manualCreate"
            >
              <i class="el-icon-edit" /> 手动配置
            </el-button>
          </div>
        </el-card>
      </div>

      <div class="examples">
        <h3>试试这些示例：</h3>
        <el-tag
          v-for="example in examples"
          :key="example"
          class="example-tag"
          @click="useExample(example)"
        >
          {{ example }}
        </el-tag>
      </div>
    </div>

    <!-- AI对话创建 -->
    <div v-if="step === 'ai-chat'" class="ai-chat-section">
      <el-card class="chat-card">
        <div slot="header" class="chat-header">
          <span><i class="el-icon-magic-stick" style="color: #1EB7E6;" /> AI 创建向导</span>
          <el-button type="text" @click="resetToWelcome">重新开始</el-button>
        </div>

        <!-- 对话历史 -->
        <div ref="chatHistory" class="chat-history">
          <div
            v-for="(msg, index) in chatMessages"
            :key="index"
            :class="['message', msg.role === 'user' ? 'user-message' : 'ai-message']"
          >
            <div class="message-avatar">
              <i :class="msg.role === 'user' ? 'el-icon-user' : 'el-icon-magic-stick'" />
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(msg.content)" />
              <!-- AI生成的配置预览 -->
              <div v-if="msg.config" class="config-preview">
                <el-divider>生成的网站配置</el-divider>
                <div class="config-grid">
                  <div class="config-item">
                    <span class="config-label">网站名称：</span>
                    <span class="config-value">{{ msg.config.name }}</span>
                  </div>
                  <div class="config-item">
                    <span class="config-label">域名建议：</span>
                    <span class="config-value">{{ msg.config.domain }}</span>
                  </div>
                  <div class="config-item">
                    <span class="config-label">前端框架：</span>
                    <span class="config-value">{{ msg.config.framework }}</span>
                  </div>
                  <div class="config-item">
                    <span class="config-label">页面数量：</span>
                    <span class="config-value">{{ msg.config.pages ? msg.config.pages.length : 0 }}</span>
                  </div>
                  <div class="config-item">
                    <span class="config-label">主色调：</span>
                    <span class="config-value">
                      <div style="display: inline-flex; align-items: center; gap: 8px;">
                        <div :style="{backgroundColor: msg.config.primary_color, width: '40px', height: '20px', borderRadius: '3px', border: '1px solid #ddd'}" />
                        {{ msg.config.primary_color }}
                      </div>
                    </span>
                  </div>
                  <div class="config-item">
                    <span class="config-label">辅助色：</span>
                    <span class="config-value">
                      <div style="display: inline-flex; align-items: center; gap: 8px;">
                        <div :style="{backgroundColor: msg.config.secondary_color, width: '40px', height: '20px', borderRadius: '3px', border: '1px solid #ddd'}" />
                        {{ msg.config.secondary_color }}
                      </div>
                    </span>
                  </div>
                </div>

                <!-- 页面列表 -->
                <div v-if="msg.config.pages && msg.config.pages.length > 0" style="margin-top: 15px;">
                  <el-divider>页面结构</el-divider>
                  <el-table :data="msg.config.pages" border size="small">
                    <el-table-column prop="title" label="页面标题" width="150" />
                    <el-table-column prop="type" label="类型" width="100" />
                    <el-table-column prop="description" label="描述" />
                  </el-table>
                </div>

                <!-- 操作按钮 -->
                <div style="margin-top: 15px; text-align: right;">
                  <el-button size="small" @click="editConfig(msg.config)">修改配置</el-button>
                  <el-button
                    type="primary"
                    size="small"
                    style="background-color: #1EB7E6; border-color: #1EB7E6;"
                    @click="confirmAndGenerate(msg.config)"
                  >
                    <i class="el-icon-check" /> 确认并生成网站
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- AI正在思考 -->
          <div v-if="aiThinking" class="message ai-message">
            <div class="message-avatar">
              <i class="el-icon-magic-stick" />
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span /><span /><span />
              </div>
            </div>
          </div>
        </div>

        <!-- 输入框 -->
        <div class="chat-input-area">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="3"
            placeholder="描述你想要的网站... 例如：我想做一个在线教育平台，需要课程展示、讲师介绍、学员评价等页面，风格要简洁专业"
            @keyup.ctrl.enter.native="sendMessage"
          />
          <div class="input-actions">
            <span class="input-tip">Ctrl + Enter 发送</span>
            <el-button
              type="primary"
              style="background-color: #1EB7E6; border-color: #1EB7E6;"
              :loading="aiThinking"
              @click="sendMessage"
            >
              <i class="el-icon-s-promotion" /> 发送
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 生成进度 -->
    <el-dialog
      title="AI正在创建网站"
      :visible.sync="generatingVisible"
      width="700px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="generateFailed || generateProgress === 100"
    >
      <div class="generating-content">
        <el-steps :active="currentGenerateStep" :process-status="generateFailed ? 'error' : 'process'" align-center>
          <el-step title="创建网站" icon="el-icon-s-home" />
          <el-step title="创建页面" icon="el-icon-document" />
          <el-step title="完成" icon="el-icon-success" />
        </el-steps>

        <div class="generate-log">
          <div v-for="(log, index) in generateLogs" :key="index" class="log-item">
            <i :class="getLogIcon(log.type)" :style="{color: getLogColor(log.type)}" />
            {{ log.message }}
          </div>
        </div>

        <el-progress
          :percentage="generateProgress"
          :status="generateProgress === 100 ? 'success' : (generateFailed ? 'exception' : undefined)"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <!-- 成功状态 -->
        <template v-if="generateProgress === 100">
          <el-button type="success" @click="viewWebsite">
            <i class="el-icon-edit" /> 编辑页面
          </el-button>
          <el-button
            type="primary"
            style="background-color: #1EB7E6; border-color: #1EB7E6;"
            @click="createAnother"
          >
            <i class="el-icon-plus" /> 再创建一个
          </el-button>
        </template>

        <!-- 失败状态 -->
        <template v-else-if="generateFailed">
          <el-button @click="generatingVisible = false">
            <i class="el-icon-close" /> 关闭
          </el-button>
          <el-button type="warning" @click="retryGenerate">
            <i class="el-icon-refresh" /> 重试
          </el-button>
        </template>

        <!-- 进行中状态 - 不显示按钮 -->
      </div>
    </el-dialog>

    <!-- 模板选择对话框 -->
    <el-dialog
      title="选择网站模板"
      :visible.sync="templateVisible"
      width="80%"
    >
      <el-row :gutter="20">
        <el-col
          v-for="template in templates"
          :key="template.id"
          :span="8"
        >
          <el-card class="template-card" shadow="hover" @click.native="useTemplate(template)">
            <div class="template-preview">
              <i :class="template.icon" style="font-size: 48px; color: #1EB7E6;" />
            </div>
            <h4>{{ template.name }}</h4>
            <p>{{ template.description }}</p>
            <el-tag size="small">{{ template.pages }}个页面</el-tag>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { AnalyzeRequirements, CreateCompleteWebsite } from '@/api/static_web/ai_create'

export default {
  name: 'AICreateWebsite',
  data() {
    return {
      step: 'welcome', // welcome, ai-chat, generating
      userInput: '',
      chatMessages: [],
      aiThinking: false,
      generatingVisible: false,
      generateFailed: false,
      lastConfig: null,
      currentGenerateStep: 0,
      generateLogs: [],
      generateProgress: 0,
      currentWebsiteId: null,
      templateVisible: false,
      examples: [
        '创建一个在线教育平台，需要课程展示、讲师介绍页面',
        '做一个产品展示网站，简洁现代风格，蓝色主题',
        '企业官网，包含关于我们、产品服务、联系我们',
        '个人博客，极简设计，黑白配色'
      ],
      templates: [
        {
          id: 1,
          name: '企业官网',
          description: '专业的企业展示网站，包含公司介绍、产品服务、新闻动态等',
          icon: 'el-icon-office-building',
          pages: 5,
          prompt: '创建一个专业的企业官网，包含首页、关于我们、产品服务、新闻动态、联系我们等页面，风格要专业大气'
        },
        {
          id: 2,
          name: '产品展示',
          description: '突出产品特性的展示网站，适合SaaS产品或实体产品',
          icon: 'el-icon-goods',
          pages: 4,
          prompt: '创建一个产品展示网站，包含首页、产品特性、定价方案、联系我们，风格要简洁现代'
        },
        {
          id: 3,
          name: '个人博客',
          description: '简洁优雅的个人博客，展示文章和个人信息',
          icon: 'el-icon-edit-outline',
          pages: 3,
          prompt: '创建一个个人博客网站，包含首页、关于我、文章列表，风格要极简优雅'
        },
        {
          id: 4,
          name: '在线教育',
          description: '课程展示和教学平台，包含课程、讲师、学员评价',
          icon: 'el-icon-reading',
          pages: 6,
          prompt: '创建一个在线教育平台，包含首页、课程展示、讲师介绍、学员评价、关于我们、联系我们'
        },
        {
          id: 5,
          name: '餐厅官网',
          description: '餐厅展示网站，包含菜单、环境、预订等',
          icon: 'el-icon-food',
          pages: 4,
          prompt: '创建一个餐厅官网，包含首页、菜单展示、餐厅环境、在线预订，风格要温馨美观'
        },
        {
          id: 6,
          name: '作品集',
          description: '展示个人或团队作品的网站',
          icon: 'el-icon-picture',
          pages: 3,
          prompt: '创建一个作品集网站，包含首页、作品展示、关于我，风格要创意时尚'
        }
      ]
    }
  },
  methods: {
    startAICreate() {
      this.step = 'ai-chat'
      this.chatMessages = [
        {
          role: 'ai',
          content: '你好！我是AI网站创建助手。\n\n请告诉我：\n1. 你想做什么类型的网站？\n2. 网站的主要用途是什么？\n3. 需要哪些页面？\n4. 有什么风格偏好？\n\n你可以用自然语言描述，我会理解并帮你创建完整的网站。'
        }
      ]
    },
    showTemplates() {
      this.templateVisible = true
    },
    manualCreate() {
      this.$router.push('/static_web/website')
    },
    useExample(example) {
      this.step = 'ai-chat'
      this.userInput = example
      this.chatMessages = [
        {
          role: 'ai',
          content: '你好！我是AI网站创建助手。请告诉我你想创建什么样的网站。'
        }
      ]
      this.$nextTick(() => {
        this.sendMessage()
      })
    },
    useTemplate(template) {
      this.templateVisible = false
      this.step = 'ai-chat'
      this.userInput = template.prompt
      this.chatMessages = [
        {
          role: 'ai',
          content: `你选择了"${template.name}"模板。我会根据这个模板为你创建网站。`
        }
      ]
      this.$nextTick(() => {
        this.sendMessage()
      })
    },
    async sendMessage() {
      if (!this.userInput.trim()) {
        return
      }

      // 添加用户消息
      this.chatMessages.push({
        role: 'user',
        content: this.userInput
      })

      const userPrompt = this.userInput
      this.userInput = ''
      this.aiThinking = true

      this.$nextTick(() => {
        this.scrollToBottom()
      })

      try {
        // 调用AI分析需求并生成配置
        const config = await this.analyzeRequirements(userPrompt)

        // 添加AI响应
        this.chatMessages.push({
          role: 'ai',
          content: '好的！我已经根据你的需求生成了网站配置方案。请查看下面的配置，如果满意可以直接生成，也可以让我修改。',
          config: config
        })

        this.aiThinking = false
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      } catch (error) {
        this.aiThinking = false
        this.$message.error('AI分析失败: ' + error.message)
      }
    },
    async analyzeRequirements(userPrompt) {
      // 调用真实的AI分析接口
      try {
        const response = await AnalyzeRequirements({
          user_prompt: userPrompt
        })

        if (response.success && response.data) {
          return response.data
        } else {
          throw new Error(response.error || 'AI分析失败')
        }
      } catch (error) {
        console.error('AI分析错误:', error)
        throw error
      }
    },
    extractWebsiteName(prompt) {
      // 简单提取逻辑，实际应该用AI
      if (prompt.includes('教育')) return '在线教育平台'
      if (prompt.includes('产品')) return '产品展示网站'
      if (prompt.includes('企业')) return '企业官网'
      if (prompt.includes('博客')) return '个人博客'
      return '我的网站'
    },
    generateDomain(prompt) {
      const timestamp = Date.now()
      return `website-${timestamp}.com`
    },
    extractWebsiteType(prompt) {
      if (prompt.includes('教育')) return '在线教育'
      if (prompt.includes('产品')) return '产品展示'
      if (prompt.includes('企业')) return '企业官网'
      return '通用'
    },
    generatePageStructure(prompt) {
      // 根据需求生成页面结构
      const pages = [
        { title: '首页', type: 'home', description: '网站主页，展示核心内容和导航' }
      ]

      if (prompt.includes('关于')) {
        pages.push({ title: '关于我们', type: 'about', description: '公司或个人介绍' })
      }
      if (prompt.includes('产品') || prompt.includes('服务')) {
        pages.push({ title: '产品服务', type: 'product', description: '产品或服务展示' })
      }
      if (prompt.includes('课程') || prompt.includes('教育')) {
        pages.push({ title: '课程展示', type: 'product', description: '课程列表和详情' })
      }
      if (prompt.includes('讲师') || prompt.includes('团队')) {
        pages.push({ title: '讲师介绍', type: 'about', description: '讲师或团队成员介绍' })
      }
      if (prompt.includes('联系')) {
        pages.push({ title: '联系我们', type: 'contact', description: '联系方式和表单' })
      }

      return pages
    },
    editConfig(config) {
      this.$prompt('请输入你想修改的内容', '修改配置', {
        inputType: 'textarea',
        inputPlaceholder: '例如：把主色调改成红色，添加一个新闻页面'
      }).then(({ value }) => {
        if (value) {
          this.userInput = value
          this.sendMessage()
        }
      })
    },
    async confirmAndGenerate(config) {
      this.generatingVisible = true
      this.currentGenerateStep = 0
      this.generateLogs = []
      this.generateProgress = 0
      this.generateFailed = false
      this.lastConfig = config

      try {
        // 创建网站结构和页面配置
        this.addLog('info', '正在创建网站结构...')
        this.currentGenerateStep = 1
        this.generateProgress = 20

        const response = await CreateCompleteWebsite({ config: config })

        if (!response.success) {
          throw new Error(response.error || '创建失败')
        }

        this.currentWebsiteId = response.data.website_id

        // 显示网站状态（新建或使用现有）
        if (response.data.website_created) {
          this.addLog('success', `网站创建成功: ${response.data.website_name} (${response.data.domain})`)
        } else {
          this.addLog('info', `使用已存在网站: ${response.data.website_name} (${response.data.domain})`)
        }

        this.currentGenerateStep = 2
        this.generateProgress = 60

        // 显示新创建的页面
        const createdPages = response.data.created_pages || []
        const skippedPages = response.data.skipped_pages || []

        if (Array.isArray(createdPages) && createdPages.length > 0) {
          createdPages.forEach(page => {
            this.addLog('success', `✓ 新建页面: ${page.title} (/${page.slug})`)
          })
        }

        // 显示跳过的页面
        if (Array.isArray(skippedPages) && skippedPages.length > 0) {
          skippedPages.forEach(page => {
            this.addLog('info', `⊙ 已存在: ${page.title} (/${page.slug})`)
          })
        }

        this.generateProgress = 90

        // 完成
        this.currentGenerateStep = 3
        const totalCreated = response.data.total_created || 0
        const totalSkipped = response.data.total_skipped || 0
        const summary = `✨ 网站处理完成！新增${totalCreated}个页面, 跳过${totalSkipped}个已存在页面`
        this.addLog('success', summary)
        this.addLog('info', '提示：进入页面编辑器可以使用AI生成页面内容')
        this.generateProgress = 100
      } catch (error) {
        this.generateFailed = true
        this.addLog('error', '创建失败: ' + error.message)
        this.$message.error('创建失败: ' + error.message)
      }
    },
    retryGenerate() {
      if (this.lastConfig) {
        this.confirmAndGenerate(this.lastConfig)
      }
    },
    titleToSlug(title) {
      const slugMap = {
        '首页': 'index',
        '关于我们': 'about',
        '产品服务': 'products',
        '课程展示': 'courses',
        '讲师介绍': 'teachers',
        '联系我们': 'contact'
      }
      return slugMap[title] || title.toLowerCase().replace(/\s+/g, '-')
    },
    addLog(type, message) {
      this.generateLogs.push({ type, message })
      this.$nextTick(() => {
        const logContainer = this.$el.querySelector('.generate-log')
        if (logContainer) {
          logContainer.scrollTop = logContainer.scrollHeight
        }
      })
    },
    getLogIcon(type) {
      const icons = {
        'info': 'el-icon-info',
        'success': 'el-icon-success',
        'error': 'el-icon-error'
      }
      return icons[type] || 'el-icon-info'
    },
    getLogColor(type) {
      const colors = {
        'info': '#909399',
        'success': '#67C23A',
        'error': '#F56C6C'
      }
      return colors[type] || '#909399'
    },
    viewWebsite() {
      // 跳转到页面列表，用户可以在那里编辑页面
      this.$router.push({
        path: '/static_web/pages',
        query: { website_id: this.currentWebsiteId }
      })
    },
    createAnother() {
      this.generatingVisible = false
      this.resetToWelcome()
    },
    resetToWelcome() {
      this.step = 'welcome'
      this.chatMessages = []
      this.userInput = ''
    },
    formatMessage(content) {
      return content.replace(/\n/g, '<br>')
    },
    scrollToBottom() {
      const container = this.$refs.chatHistory
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    }
  }
}
</script>

<style scoped>
.ai-create-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 欢迎界面 */
.welcome-section {
  text-align: center;
}

.hero {
  margin: 60px 0;
}

.hero-title {
  font-size: 48px;
  margin-bottom: 20px;
  font-weight: 600;
}

.hero-subtitle {
  font-size: 20px;
  color: #666;
}

.quick-start {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin: 40px 0;
}

.start-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.start-card:hover {
  transform: translateY(-5px);
}

.card-content {
  text-align: center;
  padding: 20px;
}

.card-icon {
  font-size: 64px;
  color: #1EB7E6;
  margin-bottom: 15px;
}

.examples {
  margin: 60px 0;
}

.example-tag {
  margin: 5px;
  cursor: pointer;
  font-size: 14px;
}

/* 对话界面 */
.ai-chat-section {
  max-width: 900px;
  margin: 0 auto;
}

.chat-card {
  min-height: 600px;
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  max-height: 500px;
  min-height: 400px;
}

.message {
  display: flex;
  margin-bottom: 20px;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
}

.user-message .message-avatar {
  background-color: #409EFF;
  color: white;
  margin-left: 10px;
}

.ai-message .message-avatar {
  background-color: #1EB7E6;
  color: white;
  margin-right: 10px;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  background-color: #f5f5f5;
}

.user-message .message-content {
  background-color: #409EFF;
  color: white;
}

.ai-message .message-content {
  background-color: #f5f5f5;
}

.message-text {
  line-height: 1.6;
}

.config-preview {
  margin-top: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
}

.config-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.config-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background-color: #fafafa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.config-label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  flex-shrink: 0;
}

.config-value {
  color: #333;
  flex: 1;
}

.typing-indicator {
  display: flex;
  gap: 5px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #1EB7E6;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

.chat-input-area {
  padding: 15px;
  border-top: 1px solid #e0e0e0;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.input-tip {
  font-size: 12px;
  color: #999;
}

/* 生成进度 */
.generating-content {
  padding: 20px 0;
}

.generate-log {
  margin: 30px 0;
  max-height: 200px;
  overflow-y: auto;
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 8px;
}

.log-item {
  padding: 5px 0;
  font-size: 14px;
}

/* 模板卡片 */
.template-card {
  cursor: pointer;
  text-align: center;
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.template-card:hover {
  transform: translateY(-5px);
}

.template-preview {
  padding: 30px;
}
</style>
